﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Collections;
using System.Text.RegularExpressions;
using System.Threading;

namespace WebCrawler
{
    internal class Crawler
    {
        private Hashtable urls = new Hashtable();
        private int count = 0;

        static void Main(string[] args)
        {
            Crawler myCrawler = new Crawler();
            string startUrl = "http://www.cnblogs.com/dstang2000/";
            //string startUrl = "https://www.meitu131.com/";
            if (args.Length > 0) startUrl = args[0];
            myCrawler.urls.Add(startUrl, false);//加入初始页面
            new Thread(myCrawler.Crawl).Start();
        }
        private void Crawl()
        {
            Console.WriteLine("Start crawling...");
            while (true)
            {
                string current = null;
                foreach (string url in urls.Keys)//找到一个还没有下载过的连接
                {
                    if ((bool)urls[url]) continue;
                    current = url;
                }
                if (current == null || count > 10) break;
                Console.WriteLine("Crawling " + current );
                //Console.WriteLine("count = "+count);
                string html = DownLoad(current);//下载
                //Console.WriteLine(html);
                urls[current] = true;
                count++;
                Parse(html);
            }
            Console.WriteLine("Crawling finished");
        }

        public string DownLoad(string url)
        {
            try
            {
                WebClient webClient = new WebClient();
                webClient.Encoding = Encoding.UTF8;
                string html = webClient.DownloadString(url);
                string fileName = count.ToString();
                //string fileName = "dataset.doc";
                File.WriteAllText(fileName, html);
                return html;
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                return "";
            }
        }

        public void Parse(string html)
        {
            string strRef = @"(href|HREF)[]*=[]*[""'][^""'#>]+[""']";
            MatchCollection matches = new Regex(strRef).Matches(html);
            foreach(Match match in matches)
            {
                //strRef = match.Value.Substring(match.Value.IndexOf('=') + 1).Trim('"', '\"','#','>');
                strRef = @"http://www.cnblogs.com/dstang2000/" + match.Value;
                if (strRef.Length == 0) continue;
                if (urls[strRef] == null) //urls[strRef] = false;
                    urls.Add(strRef, false);
            }
        }
    }
}
